<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>virtual</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C/C++ Keywords</a> &gt; <a href=
    "virtual.html">virtual</a>
  </div>

  <div class="name-format">
    virtual
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  virtual return-type name( parameter-list );
  virtual return-type name( parameter-list ) = 0;
</pre>

  <p>The virtual keyword can be used to create virtual functions, which
  can be overridden by derived classes.</p>

  <ul>
    <li>A virtual function indicates that a function can be overridden
    in a subclass, and that the overridden function will actually be
    used.</li>

    <li>When a base object pointer points to a derived object that
    contains a virtual function, the decision about which version of
    that function to call is based on the type of object pointed to by
    the pointer, and this process happens at runtime.</li>

    <li>A base object can point to different derived objects and have
    different versions of the virtual function run.</li>
  </ul>

  <p>If the function is specified as a pure virtual function (denoted
  by the = 0), it must be overridden by a derived class.</p>

  <div class="related-examples-format">
    Example code:
  </div>

  <div class="related-examples">
    <p>For example, the following code snippet shows how a child class
    can override a virtual method of its parent, and how a non-virtual
    method in the parent cannot be overridden:</p>
    <pre class="example-code">
class Base {
public:
 void nonVirtualFunc() {
   cout &lt;&lt; &quot;Base: non-virtual function&quot; &lt;&lt; endl;
 }
 virtual void virtualFunc() {
   cout &lt;&lt; &quot;Base: virtual function&quot; &lt;&lt; endl;
 }
};              

class Child : public Base {
public:
 void nonVirtualFunc() {
   cout &lt;&lt; &quot;Child: non-virtual function&quot; &lt;&lt; endl;
 }
 void virtualFunc() {
   cout &lt;&lt; &quot;Child: virtual function&quot; &lt;&lt; endl;
 }
};              

int main() {
 Base* basePointer = new Child();
 basePointer-&gt;nonVirtualFunc();
 basePointer-&gt;virtualFunc();
 return 0;
}               
</pre>

    <p>When run, the above code displays:</p>
    <pre class="example-code">
Base: non-virtual function
Child: virtual function         
</pre>
  </div>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="class.html">class</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
